package com.sea.base.utils

import android.annotation.SuppressLint
import android.app.Activity
import android.content.res.Configuration
import android.graphics.Color
import android.view.View
import android.view.WindowManager
import androidx.annotation.ColorInt
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import com.sea.base.activities.BaseFullscreenKtActivity
import com.sea.base.ext.global.dp
import com.sea.base.ext.global.postMain
import com.sea.base.ext.global.singleApplication
import com.sea.base.widget.FitsSystemWindowsFrameLayout

object StatusNavigationBarUtil {
    /**
     * 修改状态栏为沉浸式，并修改背景颜色与字体颜色
     * @param isLight true：浅色主题状态栏变为黑色字体，false：深色主题状态栏变为白色字体
     */
    fun transparencyBar(activity: Activity, isLight: Boolean = true) {
        val window = activity.window

        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
        //View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN设置为沉浸式
        //View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR 设置字体颜色为深色
        //View.SYSTEM_UI_FLAG_VISIBLE 设置字体颜色为浅色
        window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
                (if (isNightMode(activity)) View.SYSTEM_UI_FLAG_VISIBLE else View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR)
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION)
        //这里设置背景颜色，也可以设置成为透明色
        window.statusBarColor = Color.TRANSPARENT
        window.decorView.fitsSystemWindows = true

        WindowCompat.setDecorFitsSystemWindows(window, false)
        WindowInsetsControllerCompat(window, window.decorView).isAppearanceLightStatusBars = isLight
    }

    private fun isNightMode(activity: Activity): Boolean {
        val flag = activity.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
        return flag == Configuration.UI_MODE_NIGHT_YES
    }

    /**
     * 设置状态栏背景颜色 且根据背景颜色修改状态栏字体的颜色
     */
    fun setStatusBar(activity: Activity, @ColorInt color: Int, textLight: Boolean) {
        // 设置状态栏底色颜色
        activity.window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
        activity.window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
        activity.window.statusBarColor = color

        // 如果亮色，设置状态栏文字为黑色
        if (textLight) {
            activity.window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        } else {
            activity.window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE
        }
    }

    @SuppressLint("InternalInsetResource", "DiscouragedApi")
    private val statusBarResId = singleApplication.resources.getIdentifier("status_bar_height", "dimen", "android")

    /**
     * 状态栏高度
     * 建议使用：[FitsSystemWindowsFrameLayout]、[BaseFullscreenKtActivity]
     */
    @JvmStatic
    val statusBarHeight: Int
        get() {
            val px = if (statusBarResId == 0) 0 else singleApplication.resources.getDimensionPixelSize(
                statusBarResId
            )
            return if (px > 0) px else 24.dp
        }

    @SuppressLint("InternalInsetResource", "DiscouragedApi")
    private val navigationBarResId = singleApplication.resources.getIdentifier("navigation_bar_height", "dimen", "android")

    /**
     * 导航栏高度，默认20dp
     * 注意：有高度不一定不可见
     * 建议使用：[FitsSystemWindowsFrameLayout]、[BaseFullscreenKtActivity]
     */
    @JvmStatic
    val navigationBarHeight: Int
        get() {
            //ViewConfiguration.get(getApplication()).hasPermanentMenuKey()，该方法无用，仅仅表示是否有有永久导航栏而不是导航栏是否显示
            val px = if (navigationBarResId == 0) 0 else singleApplication.resources.getDimensionPixelSize(
                navigationBarResId
            )
            return if (px > 0) px else 20.dp
        }

    /**
     * 导航栏是否可见
     * 建议使用：[FitsSystemWindowsFrameLayout]、[BaseFullscreenKtActivity]
     */
    @Deprecated("已过时，请使用[FitsSystemWindowsFrameLayout]、[BaseFullscreenKtActivity]")
    private fun isNavigationBarVisible(activity: Activity): Boolean {
        activity.window.decorView.rootWindowInsets?.let {
            val bottom = WindowInsetsCompat.toWindowInsetsCompat(it).getInsets(WindowInsetsCompat.Type.navigationBars()).bottom
            return bottom != 0
        }
        //手机设备没有导航栏时，可能返回一个较小值
        return navigationBarHeight >= 20.dp
    }

    /**
     * 导航栏可见性回调监听，会占用decorView的setOnApplyWindowInsetsListener
     * 建议使用：[FitsSystemWindowsFrameLayout]、[BaseFullscreenKtActivity]
     * @param onVisibleCallback 是否可见监听，调用时会立即回调，后续变化会重复回调
     */
    @Deprecated("已过时，请使用[FitsSystemWindowsFrameLayout]、[BaseFullscreenKtActivity]")
    private fun setNavigationBarVisibleChangedListener(activity: Activity, onVisibleCallback: (Boolean) -> Unit) {
        val run = object : Runnable {
            private var isVisible: Boolean? = null
            override fun run() {
                val iv = isNavigationBarVisible(activity)
                if (isVisible != iv) {
                    isVisible = iv
                    onVisibleCallback.invoke(iv)
                }
            }
        }
        activity.window.decorView.setOnApplyWindowInsetsListener { _, insets ->
            postMain(run)
            insets
        }
        postMain(run)
    }
}